package com.chenwc.serialassistant.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * 获取配置文件的内容
 *
 * @author chenwc
 */
public class LoadConfigInfo {

    private final static Logger logger = LoggerFactory.getLogger(LoadConfigInfo.class);

    /**
     * 串口读取数据的字符编码
     */
    private final String serialPortReadDataCharsetName;
    /**
     * 串口发送数据的字符编码
     */
    private String SerialPortSendDataCharsetName;

    /**
     * 波特率
     */
    private List<Integer> BaudRate;
    /**
     * 数据位
     */
    private List<Integer> DataBits;
    /**
     * 停止位
     */
    private List<String> StopBits;
    /**
     * 校验方式
     */
    private List<String> Parity;

    /**
     * 上一次打开文件的目录路径
     */
    private String LastFilePath;

    private String Font;
    private String FontColor;
    private String FontSize;
    private String BackGroundColor;

    private boolean dateFormat;
    private boolean displayBufferUpperLimit200K;
    private boolean displayBufferUpperLimit500K;
    private boolean displayBufferUpperLimit1M;
    private boolean displayBufferUpperLimit2M;
    private boolean displayBufferUpperLimit5M;
    private boolean enterSend;
    private boolean sendButtonValue;
    private boolean displayButtonValue;
    private boolean sendEnterAndNewlineCharacter;
    private boolean lineFeedCheckBox;

    private String serialPortName;
    private String comParity;
    private String comStopBits;
    private int comDataBits;
    private int comBaudRate;

    private int MaxReadDataTimeOut;

    private int ReceiveSubcontractingSize;

    private final Properties properties = new Properties();

    public LoadConfigInfo() {
        try {
            File file = new File("config.properties");
            if (!file.exists()) {
                logger.info("Jar 包所在目录下不存在 config.properties 配置文件，创建配置文件！");
                if (file.createNewFile()) {
                    logger.info("在 Jar 包所在目录下创建 config.properties 配置文件成功");
                    properties.load(LoadConfigInfo.class.getClassLoader().getResourceAsStream("config.properties"));
                    ///保存属性到创建的config.properties文件
                    FileOutputStream oFile = new FileOutputStream(file);
                    properties.store(oFile, "");
                    oFile.close();
                } else {
                    logger.info("在 Jar 包所在目录下创建 config.properties 配置文件失败，请检查文件夹权限！");
                }

            } else {
                logger.info("Jar 包所在目录下存在 config.properties 配置文件，读取配置文件！");
                InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()));
                properties.load(in);
                in.close();
            }
        } catch (Exception e) {
            logger.info("读取 Jar 包所在目录的 config.properties 配置文件失败！");
            e.printStackTrace();
        }

        serialPortReadDataCharsetName = properties.getProperty("SerialPortReadDataCharsetName");
        SerialPortSendDataCharsetName = properties.getProperty("SerialPortSendDataCharsetName");

        String[] baudRateString = properties.getProperty("BaudRate").replace(" ", "").split(",");
        List<Integer> baudRateInteger = new ArrayList<>();
        for (String b : baudRateString) {
            baudRateInteger.add(Integer.valueOf(b));
        }
        BaudRate = baudRateInteger;

        String[] dataBitsString = properties.getProperty("DataBits").replace(" ", "").split(",");
        List<Integer> DataBitsInteger = new ArrayList<>();
        for (String d : dataBitsString) {
            DataBitsInteger.add(Integer.valueOf(d));
        }
        DataBits = DataBitsInteger;

        StopBits = Arrays.asList(properties.getProperty("StopBits").replace(" ", "").split(","));
        Parity = Arrays.asList(properties.getProperty("Parity").replace(" ", "").split(","));

        if (null == properties.getProperty("LastFilePath")) {
            LastFilePath = "";
        } else {
            LastFilePath = properties.getProperty("LastFilePath");
        }

        Font = properties.getProperty("Font");
        FontColor = properties.getProperty("FontColor");
        FontSize = properties.getProperty("FontSize");
        BackGroundColor = properties.getProperty("BackGroundColor");

        dateFormat = Boolean.parseBoolean(properties.getProperty("dateFormat"));
        displayBufferUpperLimit200K = Boolean.parseBoolean(properties.getProperty("displayBufferUpperLimit200K"));
        displayBufferUpperLimit500K = Boolean.parseBoolean(properties.getProperty("displayBufferUpperLimit500K"));
        displayBufferUpperLimit1M = Boolean.parseBoolean(properties.getProperty("displayBufferUpperLimit1M"));
        displayBufferUpperLimit2M = Boolean.parseBoolean(properties.getProperty("displayBufferUpperLimit2M"));
        displayBufferUpperLimit5M = Boolean.parseBoolean(properties.getProperty("displayBufferUpperLimit5M"));
        enterSend = Boolean.parseBoolean(properties.getProperty("enterSend"));
        sendButtonValue = Boolean.parseBoolean(properties.getProperty("sendButtonValue"));
        displayButtonValue = Boolean.parseBoolean(properties.getProperty("displayButtonValue"));
        sendEnterAndNewlineCharacter = Boolean.parseBoolean(properties.getProperty("sendEnterAndNewlineCharacter"));
        lineFeedCheckBox = Boolean.parseBoolean(properties.getProperty("lineFeedCheckBox"));

        serialPortName = properties.getProperty("serialPortName");
        comParity = properties.getProperty("comParity");
        comStopBits = properties.getProperty("comStopBits");
        comDataBits = Integer.parseInt(properties.getProperty("comDataBits"));
        comBaudRate = Integer.parseInt(properties.getProperty("comBaudRate"));
        MaxReadDataTimeOut = Integer.parseInt(properties.getProperty("MaxReadDataTimeOut"));
        ReceiveSubcontractingSize = Integer.parseInt(properties.getProperty("ReceiveSubcontractingSize"));
    }

    public int getMaxReadDataTimeOut() {
        return MaxReadDataTimeOut;
    }

    public void setMaxReadDataTimeOut(int maxReadDataTimeOut) {
        MaxReadDataTimeOut = maxReadDataTimeOut;
        saveProperties("MaxReadDataTimeOut", String.valueOf(maxReadDataTimeOut));
    }

    public String getSerialPortReadDataCharsetName() {
        return serialPortReadDataCharsetName;
    }

    public void setSerialPortReadDataCharsetName(String serialPortReadDataCharsetName) {
        serialPortReadDataCharsetName = serialPortReadDataCharsetName;
        saveProperties("SerialPortReadDataCharsetName", serialPortReadDataCharsetName);
    }

    public String getSerialPortSendDataCharsetName() {
        return SerialPortSendDataCharsetName;
    }

    public void setSerialPortSendDataCharsetName(String serialPortSendDataCharsetName) {
        SerialPortSendDataCharsetName = serialPortSendDataCharsetName;
        saveProperties("SerialPortSendDataCharsetName", SerialPortSendDataCharsetName);
    }

    public List<Integer> getBaudRate() {
        return BaudRate;
    }

    public void setBaudRate(List<Integer> baudRate) {
        BaudRate = baudRate;
    }

    public List<Integer> getDataBits() {
        return DataBits;
    }

    public void setDataBits(List<Integer> dataBits) {
        DataBits = dataBits;
    }

    public List<String> getStopBits() {
        return StopBits;
    }

    public void setStopBits(List<String> stopBits) {
        StopBits = stopBits;
    }

    public List<String> getParity() {
        return Parity;
    }

    public void setParity(List<String> parity) {
        Parity = parity;
    }

    public String getLastFilePath() {
        return LastFilePath;

    }

    public void setLastFilePath(String lastFilePath) {
        LastFilePath = lastFilePath;
        saveProperties("LastFilePath", lastFilePath);
    }

    public String getFont() {
        return Font;
    }

    public void setFont(String font) {
        Font = font;
        saveProperties("Font", font);
    }

    public String getFontColor() {
        return FontColor;
    }

    public void setFontColor(String fontColor) {
        FontColor = fontColor;
        saveProperties("FontColor", fontColor);
    }

    public String getFontSize() {
        return FontSize;
    }

    public void setFontSize(String fontSize) {
        FontSize = fontSize;
        saveProperties("FontSize", fontSize);
    }

    public String getBackGroundColor() {
        return BackGroundColor;
    }

    public void setBackGroundColor(String backGroundColor) {
        BackGroundColor = backGroundColor;
        saveProperties("BackGroundColor", backGroundColor);
    }

    public boolean isDateFormat() {
        return dateFormat;
    }

    public void setDateFormat(boolean dateFormat) {
        this.dateFormat = dateFormat;
        saveProperties("dateFormat", String.valueOf(dateFormat));
    }

    public boolean isDisplayBufferUpperLimit200K() {
        return displayBufferUpperLimit200K;
    }

    public void setDisplayBufferUpperLimit200K(boolean displayBufferUpperLimit200K) {
        this.displayBufferUpperLimit200K = displayBufferUpperLimit200K;
        saveProperties("displayBufferUpperLimit200K", String.valueOf(displayBufferUpperLimit200K));
    }

    public boolean isDisplayBufferUpperLimit500K() {
        return displayBufferUpperLimit500K;
    }

    public void setDisplayBufferUpperLimit500K(boolean displayBufferUpperLimit500K) {
        this.displayBufferUpperLimit500K = displayBufferUpperLimit500K;
        saveProperties("displayBufferUpperLimit500K", String.valueOf(displayBufferUpperLimit500K));
    }

    public boolean isDisplayBufferUpperLimit1M() {
        return displayBufferUpperLimit1M;
    }

    public void setDisplayBufferUpperLimit1M(boolean displayBufferUpperLimit1M) {
        this.displayBufferUpperLimit1M = displayBufferUpperLimit1M;
        saveProperties("displayBufferUpperLimit1M", String.valueOf(displayBufferUpperLimit1M));
    }

    public boolean isDisplayBufferUpperLimit2M() {
        return displayBufferUpperLimit2M;
    }

    public void setDisplayBufferUpperLimit2M(boolean displayBufferUpperLimit2M) {
        this.displayBufferUpperLimit2M = displayBufferUpperLimit2M;
        saveProperties("displayBufferUpperLimit2M", String.valueOf(displayBufferUpperLimit2M));
    }

    public boolean isDisplayBufferUpperLimit5M() {
        return displayBufferUpperLimit5M;
    }

    public void setDisplayBufferUpperLimit5M(boolean displayBufferUpperLimit5M) {
        this.displayBufferUpperLimit5M = displayBufferUpperLimit5M;
        saveProperties("displayBufferUpperLimit5M", String.valueOf(displayBufferUpperLimit5M));
    }

    public boolean isEnterSend() {
        return enterSend;
    }

    public void setEnterSend(boolean enterSend) {
        this.enterSend = enterSend;
        saveProperties("enterSend", String.valueOf(enterSend));
    }

    public boolean isSendButtonValue() {
        return sendButtonValue;
    }

    public void setSendButtonValue(boolean sendButtonValue) {
        this.sendButtonValue = sendButtonValue;
        saveProperties("sendButtonValue", String.valueOf(sendButtonValue));
    }

    public boolean isDisplayButtonValue() {
        return displayButtonValue;
    }

    public void setDisplayButtonValue(boolean displayButtonValue) {
        this.displayButtonValue = displayButtonValue;
        saveProperties("displayButtonValue", String.valueOf(displayButtonValue));
    }

    public boolean isSendEnterAndNewlineCharacter() {
        return sendEnterAndNewlineCharacter;
    }

    public void setSendEnterAndNewlineCharacter(boolean sendEnterAndNewlineCharacter) {
        this.sendEnterAndNewlineCharacter = sendEnterAndNewlineCharacter;
        saveProperties("sendEnterAndNewlineCharacter", String.valueOf(sendEnterAndNewlineCharacter));
    }

    public boolean isLineFeedCheckBox() {
        return lineFeedCheckBox;
    }

    public void setLineFeedCheckBox(boolean lineFeedCheckBox) {
        this.lineFeedCheckBox = lineFeedCheckBox;
        saveProperties("lineFeedCheckBox", String.valueOf(lineFeedCheckBox));
    }

    public String getSerialPortName() {
        return serialPortName;
    }

    public void setSerialPortName(String serialPortName) {
        this.serialPortName = serialPortName;
        saveProperties("serialPortName", serialPortName);
    }

    public String getComParity() {
        return comParity;
    }

    public void setComParity(String comParity) {
        this.comParity = comParity;
        saveProperties("comParity", comParity);
    }

    public String getComStopBits() {
        return comStopBits;
    }

    public void setComStopBits(String comStopBits) {
        this.comStopBits = comStopBits;
        saveProperties("comStopBits", comStopBits);
    }

    public int getComDataBits() {
        return comDataBits;
    }

    public void setComDataBits(int comDataBits) {
        this.comDataBits = comDataBits;
        saveProperties("comDataBits", String.valueOf(comDataBits));
    }

    public int getComBaudRate() {
        return comBaudRate;
    }

    public void setComBaudRate(int comBaudRate) {
        this.comBaudRate = comBaudRate;
        saveProperties("comBaudRate", String.valueOf(comBaudRate));
    }

    public int getReceiveSubcontractingSize() {
        return ReceiveSubcontractingSize;
    }

    public void setReceiveSubcontractingSize(int receiveSubcontractingSize) {
        ReceiveSubcontractingSize = receiveSubcontractingSize;
        saveProperties("ReceiveSubcontractingSize", String.valueOf(receiveSubcontractingSize));
    }

    private void saveProperties(String key, String value) {
        try {
            File file = new File("config.properties");
            ///保存属性到config.properties文件
            //true表示追加打开
            FileOutputStream oFile = new FileOutputStream(file);
            properties.setProperty(key, value);
            properties.store(oFile, "update config.properties!");
            oFile.close();
        } catch (Exception e) {
            logger.error("SaveProperties Error: {}", e.getMessage());
        }
    }
}
